package com.tokenmaster.aitrade.market.okex.future;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.tokenmaster.aitrade.market.HttpUtilManager;
import com.tokenmaster.aitrade.market.okex.MD5Util;

/**
 * @ClassName: OkexFutureRest
 * @Description: 封装签名方法，http请求
 * @author 余洋
 * @date 2018年5月12日 下午7:09:09
 *
 */
public class OkexFutureRest implements IFutureRestApi {

	private String secret_key;

	private String api_key;

	private String url_prex;

	public String requestUrl = "";

	/**
	 * 构造函数：仅传入地址
	 *
	 * @param url_prex
	 */
	public OkexFutureRest(String url_prex) {
		this.url_prex = url_prex;
	}

	/**
	 * 构造函数：需要传入Apikey,SecretKey
	 *
	 * @param url_prex
	 * @param api_key
	 * @param secret_key
	 */
	public OkexFutureRest(String url_prex, String api_key, String secret_key) {
		this.api_key = api_key;
		this.secret_key = secret_key;
		this.url_prex = url_prex;
	}

	/**
	 * 期货行情URL
	 */
	private final String FUTURE_TICKER_URL = "/api/v1/future_ticker.do";

	private final String FUTURE_KLINE_URL = "/api/v1/future_kline.do";

	/**
	 * 期货账户信息URL
	 */
	private final String FUTURE_USERINFO_URL = "/api/v1/future_userinfo.do";

	/**
	 * 逐仓期货账户信息URL
	 */
	private final String FUTURE_USERINFO_4FIX_URL = "/api/v1/future_userinfo_4fix.do";

	/**
	 * 用户期货订单信息查询URL
	 */
	private final String FUTURE_ORDER_INFO_URL = "/api/v1/future_order_info.do";

	/**
	 * 期货下单URL
	 */
	private final String FUTURE_TRADE_URL = "/api/v1/future_trade.do";
	/**
	 * 期货取消订单URL
	 */
	private final String FUTURE_CANCEL_URL = "/api/v1/future_cancel.do";

	/**
	 * 账户资金划转URL
	 */
	private final String FUTURE_DEVOLVE_URL = "/api/v1/future_devolve.do";

	public String future_ticker(String symbol, String contractType) throws IOException {
		HttpUtilManager httpUtilManager = HttpUtilManager.getInstance();
		String param = "";
        symbol = symbol.toLowerCase();
		param = "symbol=" + symbol + "&contract_type=" + contractType;

		String result = httpUtilManager.requestHttpGet(url_prex, FUTURE_TICKER_URL, param);
		return result;
	}

	public String future_kline(String symbol, String contract_type, String type, Integer size) {
		HttpUtilManager httpUtilManager = HttpUtilManager.getInstance();
		String param = "";
		symbol = symbol.toLowerCase();
		param = "symbol=" + symbol + "&type=" + type + "&contract_type=" + contract_type;
        if (size != null) {
            param = param + "&size=" + size;
        }
		String result = "";
		try {
			result = httpUtilManager.requestHttpGet(url_prex, FUTURE_KLINE_URL, param);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public String future_userinfo_4fix() throws IOException {
		// 构造参数签名
		Map<String, String> params = new HashMap<String, String>();

		params.put("api_key", api_key);

		String sign = MD5Util.buildMysignV1(params, this.secret_key);
		params.put("sign", sign);

		// 发送post请求

		HttpUtilManager httpUtil = HttpUtilManager.getInstance();
		String result = httpUtil.requestHttpPost(url_prex, this.FUTURE_USERINFO_4FIX_URL, params);
		// System.out.println(result);
		return result;
	}

	public String future_trade(String symbol, String contractType, String price, String amount, String type,
			String matchPrice) throws IOException {
		// 构造参数签名

		Map<String, String> params = new HashMap<String, String>();
		if (!symbol.isEmpty()) {
			params.put("symbol", symbol);
		}
		if (!contractType.isEmpty()) {
			params.put("contract_type", contractType);
		}
		if (!api_key.isEmpty()) {
			params.put("api_key", api_key);
		}
		if (!price.isEmpty()) {
			params.put("price", price);
		}
		if (!amount.isEmpty()) {
			params.put("amount", amount);
		}
		if (!type.isEmpty()) {
			params.put("type", type);
		}
		if (!matchPrice.isEmpty()) {
			params.put("match_price", matchPrice);
		}
		String sign = MD5Util.buildMysignV1(params, secret_key);
		params.put("sign", sign);
		// 发送post请求

		HttpUtilManager httpUtil = HttpUtilManager.getInstance();
		String result = httpUtil.requestHttpPost(url_prex, this.FUTURE_TRADE_URL, params);
		// System.out.println(result);
		return result;
	}

	public String future_order_info(String symbol, String contractType, String orderId, String status,
			String currentPage, String pageLength) throws IOException {

		// 构造参数签名
		Map<String, String> params = new HashMap<String, String>();
		if (!contractType.isEmpty()) {
			params.put("contract_type", contractType);
		}
		if (!currentPage.isEmpty()) {
			params.put("current_page", currentPage);
		}
		if (!orderId.isEmpty()) {
			params.put("order_id", orderId);
		}
		if (!api_key.isEmpty()) {
			params.put("api_key", api_key);
		}
		if (!pageLength.isEmpty()) {
			params.put("page_length", pageLength);
		}
		if (!symbol.isEmpty()) {
			params.put("symbol", symbol);
		}
		if (!status.isEmpty()) {
			params.put("status", status);
		}

		String sign = MD5Util.buildMysignV1(params, secret_key);
		params.put("sign", sign);
		// 发送post请求

		HttpUtilManager httpUtil = HttpUtilManager.getInstance();
		String result = httpUtil.requestHttpPost(url_prex, this.FUTURE_ORDER_INFO_URL, params);
		System.out.println(result);

		return result;
	}

	public String future_devolve(String symbol, String type, String amount) throws IOException {
		// 构造参数签名
		Map<String, String> params = new HashMap<String, String>();
		if (!symbol.isEmpty()) {
			params.put("symbol", symbol);
		}
		if (!type.isEmpty()) {
			params.put("type", type);
		}
		if (!amount.isEmpty()) {
			params.put("amount", amount);
		}
		if (!api_key.isEmpty()) {
			params.put("api_key", api_key);
		}

		String sign = MD5Util.buildMysignV1(params, secret_key);
		params.put("sign", sign);

		HttpUtilManager httpUtil = HttpUtilManager.getInstance();
		String result = httpUtil.requestHttpPost(url_prex, this.FUTURE_DEVOLVE_URL, params);
		System.out.println(result);
		return result;
	}

	public String future_cancel(String symbol, String contractType, String orderId) throws IOException {
		// 构造参数签名
		Map<String, String> params = new HashMap<String, String>();
		if (!contractType.isEmpty()) {
			params.put("contract_type", contractType);
		}
		if (!orderId.isEmpty()) {
			params.put("order_id", orderId);
		}
		if (!api_key.isEmpty()) {
			params.put("api_key", api_key);
		}
		if (!symbol.isEmpty()) {
			params.put("symbol", symbol);
		}
		String sign = MD5Util.buildMysignV1(params, secret_key);

		params.put("sign", sign);
		// 发送post请求

		HttpUtilManager httpUtil = HttpUtilManager.getInstance();
		String result = httpUtil.requestHttpPost(url_prex, FUTURE_CANCEL_URL, params);
		// System.out.println(result);
		return result;
	}

	public String getApi_key() {
		return api_key;
	}

	public void setApi_key(String api_key) {
		this.api_key = api_key;
	}

	public String getSecret_key() {
		return secret_key;
	}

	public void setSecret_key(String secret_key) {
		this.secret_key = secret_key;
	}

	public String getUrl_prex() {
		return url_prex;
	}

	public void setUrl_prex(String url_prex) {
		this.url_prex = url_prex;
	}

	public void makeSign(String signStr) {

		// // 待签名字符串
		// String signStr = "api_key=" + api_key + "&" + symbol + "&" + type +
		// "&secret_key=" + Secretkey;
		//
		// logger.info(signStr);
		//
		// String signature = MD5(signStr);
		// requestUrl = baseUrl + queryUrl + "api_key=" + apiKey + "&" + symbol
		// + "&" + type + "&secret_key=" + Secretkey
		// + "&sign=" + signature;
		//
		// logger.info(requestUrl);
	}

	private String MD5(String s) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(s.getBytes("utf-8"));
			return toHex(bytes);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String toHex(byte[] bytes) {

		final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
		StringBuilder ret = new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
			ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
		}
		return ret.toString();
	}

	public String SHA256(byte[] data, byte[] key) {
		try {
			SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA256");
			Mac mac = Mac.getInstance("HmacSHA256");
			mac.init(signingKey);
			return byte2hex(mac.doFinal(data));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String byte2hex(byte[] b) {
		StringBuilder hs = new StringBuilder();
		String stmp;
		for (int n = 0; b != null && n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0XFF);
			if (stmp.length() == 1)
				hs.append('0');
			hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

}
